/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.jsch.service

import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.Session
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import javax.inject.Inject
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory
import cool.taomu.toolkit.jsch.service.SftpProgresssMonitorImpl.Callback

@Accessors
class Sftp implements AutoCloseable {
	val static LOG = LoggerFactory.getLogger(Ssh);
	var ChannelSftp sftp = null;
	IJschConnection ds;
	Session session;
	
	@Inject
	new(IJschConnection ds) {
		LOG.info("创建SFTP Channel");
		this.ds = ds;

	}

	override close() throws Exception {
		if (sftp !== null) {
			LOG.info("关闭SFTP Channel");
			this.sftp.disconnect
			this.session.disconnect
		}
	}

	private def connect() {
		this.session = ds.resource;
		var channel = session.openChannel("sftp");
		sftp = channel as ChannelSftp;
		sftp.connect;
	}

	def get(String file) {
		this.connect;
		var bos = new ByteArrayOutputStream();
		this.sftp.get(file, bos, new SftpProgresssMonitorImpl);
		return bos.toByteArray;
	}

	def get(String src, String dst) {
		this.connect;
		this.sftp.get(src, dst, new SftpProgresssMonitorImpl);
	}

	def void put(String file, byte[] content) {
		this.connect;
		var bis = new ByteArrayInputStream(content);
		this.sftp.put(bis, file, new SftpProgresssMonitorImpl);
	}

	def void put(String src, String dst) {
		this.connect;
		this.sftp.put(src, dst, new SftpProgresssMonitorImpl);
	}
	
	def void put(InputStream input,String dst){
		this.connect;
		this.sftp.put(input, dst, new SftpProgresssMonitorImpl);
	}
	/**
	 *  ChannelSftp.OVERWRITE;
	 *  ChannelSftp.RESUME;
	 *	ChannelSftp.APPEND;
	 */
	def void put(InputStream input,String dst,int mode){
		this.connect;
		this.sftp.put(input, dst, new SftpProgresssMonitorImpl,mode);
	}
	
	/**
	 *  ChannelSftp.OVERWRITE;
	 *  ChannelSftp.RESUME;
	 *	ChannelSftp.APPEND;
	 */
	def void put(InputStream input,String dst,int mode,Callback callback){
		this.connect;
		this.sftp.put(input, dst, new SftpProgresssMonitorImpl(callback),mode);
	}
	
	def ChannelSftp getChannelSftp(){
		this.connect;
		return this.sftp;
	}
}
